package com.example.administrator.u17.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.u17.R;
import com.example.administrator.u17.activity.VIPDetailActivity;
import com.example.administrator.u17.activity.ZhangJieActivity;
import com.example.administrator.u17.adapter.VIPFragmentAdapter;
import com.example.administrator.u17.config.NetConfig;
import com.example.administrator.u17.db.VIPDb;
import com.example.administrator.u17.model.Comics;


import com.example.administrator.u17.model.VIPData1;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */

public class VIPFragment extends Fragment {


    private PullToRefreshListView pullToLv;
    private VIPFragmentAdapter adapter;
    private ArrayList<VIPData1.DataBean.ReturnDataBean.ComicsBean> mList;
    private int page;
    private DbManager dbManager;
    private String path;
    private VIPData1 vipData;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view=inflater.inflate(R.layout.fragment_vip,null);
        initView(view);
        initData();
        setData();
        setListener();


        return view;
    }

    private void initView(View v) {

        mList=new ArrayList<>();
        adapter=new VIPFragmentAdapter(getActivity(),mList);
        pullToLv= (PullToRefreshListView) v.findViewById(R.id.VIP_pullTo_shop_lv_2);
        pullToLv.setAdapter(adapter);
        pullToLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent=new Intent(getActivity(), ZhangJieActivity.class);
                String id1=mList.get(position-1).getComicId()+"";
                intent.putExtra("id",id1);
                intent.putExtra("count",mList.get(position-1).getConTag());
                startActivity(intent);
            }
        });


    }

    private void initData() {

        dbManager= x.getDb(new DbManager.DaoConfig());
        try {
            dbManager.save(new Comics());
        } catch (DbException e) {
            e.printStackTrace();
        }

        loadData();

    }


    public void loadData(){

        path= NetConfig.VIP_PATH+page;
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                if (page==1) {
                    mList.clear();
                }

                page++;
                vipData = new Gson().fromJson(s,VIPData1.class);

                mList.addAll(vipData.getData().getReturnData().getComics());



                //存入数据库
                VIPDb vipDb=new VIPDb();
                vipDb.json=s;
                vipDb.path=path;
                vipDb.time=System.currentTimeMillis();

                Log.d("TAG", "onSuccess: "+path);
                try {
                    dbManager.save(vipDb);
                } catch (DbException e) {
                    e.printStackTrace();
                }

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                try {
                    List<VIPDb> db=dbManager.selector(VIPDb.class).where("path","=",path)
                            .findAll();
                    long duration=System.currentTimeMillis();
                    if (duration>1000*60*30){

                        dbManager.delete(VIPDb.class, WhereBuilder.b("path","=",path));

                    }else {
                        VIPData1 vData=new Gson().fromJson(db.get(0).json,VIPData1.class);
                        mList.addAll(vData.getData().getReturnData().getComics());
                        adapter.notifyDataSetChanged();
                        Toast.makeText(getActivity(), ""+path, Toast.LENGTH_SHORT).show();
                        pullToLv.onRefreshComplete();
                        return;
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

                pullToLv.onRefreshComplete();
            }
        });


    }
    private void setData() {

        pullToLv.setMode(PullToRefreshBase.Mode.BOTH);
        pullToLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                loadData();
                page=1;
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                loadData();
            }
        });
    }

    private void setListener() {

        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat simpleDataFormate=new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");;
        ILoadingLayout iLoding=pullToLv.getLoadingLayoutProxy();
        iLoding.setRefreshingLabel("正在拼命加载中。。。");
        iLoding.setLastUpdatedLabel("最后加载时间"+simpleDataFormate.format(calendar.getTime()));


    }
}
